package com.fastadmin.wechat;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fastadmin.config.security.annotation.AnonymousAccess;
import com.fastadmin.mapper.impl.FUserMapper;
import com.fastadmin.pojo.FUser;
import com.fastadmin.service.FUserService;
import com.fastadmin.service.QiniuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static com.fastadmin.common.FAConst.WeChatMiNi.*;

@RestController
@RequiredArgsConstructor
@Slf4j
public class MFUserController extends FBaseController {
    public final FUserMapper fUserMapper;
    public final FUserService fUserService;
    public final QiniuService qiniuService;



    @RequestMapping("/f/fuser/login")
    @AnonymousAccess
    public Object userInfo(@RequestParam String code) {
        HttpResponse response = HttpUtil.createGet(REQUEST_URL)
                .form("appid", APPID)
                .form("secret", SECRET)
                .form("grant_type", GRANT_TYPE)
                .form("js_code", code)
                .execute();
        if (response.isOk()) {
            Map<String, String> resultMap;
            log.debug(response.body());
            JSONObject jsonObject = JSONUtil.parseObj(response.body());
            String session_key = jsonObject.getStr("session_key");
            String openid = jsonObject.getStr("openid");
            FUser findUser = fUserMapper.findByOpenId(openid);
            if (ObjectUtil.isNull(findUser)) {
                log.debug("新用户！");
                FUser fUser = FUser.builder().open_id(openid).build();
                fUserMapper.save(fUser);
                resultMap = fUserService.doLogin(fUser);
            }else{
                log.debug("已经存在了此用户！");
                resultMap = fUserService.doLogin(findUser);
            }
            resultMap.put("open_id", openid);
            resultMap.put("session_key", session_key);
            return ok(resultMap);
        }
        return error();
    }

    @RequestMapping("/f/fuser/info")
    @AnonymousAccess
    public Object info(String openid, Integer gender, String avatarUrl, String city, String nickName) {
        FUser dbUser = fUserMapper.findByOpenId(openid);
        if (StrUtil.equals(nickName, "未授权") || StrUtil.equals(dbUser.getNickname(), "未授权")) {
            return ok();
        }
        if (StrUtil.containsAny(dbUser.getAvatar(), "http")) {
            return ok();
        }

        HttpResponse response = HttpUtil.createGet(URLUtil.normalize(avatarUrl)).execute();
        if (response.isOk()) {
            log.debug("更换头像了{}");
            Map<String, Object> resultMap = qiniuService.uploadInputStream(response.bodyStream());
            if (resultMap.containsKey("qiniu_path")) {
                String qiniu_path = MapUtil.getStr(resultMap, "qiniu_path");
                avatarUrl = qiniu_path;
            }
        }
        Long id = fUserMapper.findByOpenId(openid).getId();
        FUser user = FUser.builder()
                .id(id)
                .open_id(openid)
                .sex(gender)
                .avatar(avatarUrl)
                .nickname(nickName)
                .city(city).build();
        fUserMapper.update(user);
        return ok();
    }



}
